import os
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.filechooser import FileChooserListView
from kivy.uix.popup import Popup


class NotebookLayout(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = 'vertical'

        # 文本输入框
        self.text_input = TextInput(multiline=True)
        self.add_widget(self.text_input)

        # 按钮布局
        button_layout = BoxLayout(orientation='horizontal', size_hint_y=0.1)

        # 导入按钮
        import_button = Button(text='导入文件')
        import_button.bind(on_press=self.import_file)
        button_layout.add_widget(import_button)

        # 导出按钮
        export_button = Button(text='导出文件')
        export_button.bind(on_press=self.export_file)
        button_layout.add_widget(export_button)

        self.add_widget(button_layout)

    def import_file(self, instance):
        # 创建文件选择器
        file_chooser = FileChooserListView()
        # 创建确认按钮
        confirm_button = Button(text='确认导入', size_hint_y=0.1)
        confirm_button.bind(on_press=lambda x: self.load_file(file_chooser.path, file_chooser.selection))

        # 创建弹窗
        content = BoxLayout(orientation='vertical')
        content.add_widget(file_chooser)
        content.add_widget(confirm_button)
        popup = Popup(title='选择要导入的文件', content=content, size_hint=(0.9, 0.9))
        popup.open()

    def load_file(self, path, selection):
        if selection:
            file_path = os.path.join(path, selection[0])
            try:
                with open(file_path, 'r', encoding='utf-8') as file:
                    self.text_input.text = file.read()
            except Exception as e:
                print(f"导入文件时出错: {e}")

    def export_file(self, instance):
        # 创建文件选择器
        file_chooser = FileChooserListView()
        # 创建确认按钮
        confirm_button = Button(text='确认导出', size_hint_y=0.1)
        confirm_button.bind(on_press=lambda x: self.save_file(file_chooser.path, file_chooser.selection))

        # 创建弹窗
        content = BoxLayout(orientation='vertical')
        content.add_widget(file_chooser)
        content.add_widget(confirm_button)
        popup = Popup(title='选择导出位置', content=content, size_hint=(0.9, 0.9))
        popup.open()

    def save_file(self, path, selection):
        if selection:
            file_path = os.path.join(path, selection[0])
            try:
                with open(file_path, 'w', encoding='utf-8') as file:
                    file.write(self.text_input.text)
            except Exception as e:
                print(f"导出文件时出错: {e}")


class NotebookApp(App):
    def build(self):
        return NotebookLayout()


if __name__ == '__main__':
    NotebookApp().run()
    